import Json from '@/data/ResultJson'
import { AutoId } from '@/data/AutoId'
import { getActorByIdAjax } from '@/data/ActorData'
import { getCategoryByIdAjax } from '@/data/CategoryData'
const filmList = [
  { id: 1, name: '哪吒之魔童降世', actorId: 1, categoryId: 1, profile: '哪吒之魔童降世', status: 1 },
  { id: 2, name: '云边的小卖部', actorId: 2, categoryId: 2, profile: '云边的小卖部', status: 1 },
  { id: 3, name: '淮水竹亭', actorId: 3, categoryId: 3, profile: '淮水竹亭', status: 2 }
]
function getIndexById (id) {
  id = parseInt(id)
  let index = -1
  for (let i = 0; i < filmList.length; i++) {
    if (filmList[i].id === id) {
      index = i
      break
    }
  }
  if (index === -1) {
    return Json.error('编号异常！')
  }
  return index
}

export function getFilmListAjax (searchInfo = {}) {
  let dataList = filmList.filter(item => item.name === searchInfo.name || !searchInfo.name)
  dataList = dataList.filter(item => item.actorId === searchInfo.actorId || !searchInfo.actorId)
  dataList = dataList.filter(item => item.categoryId === searchInfo.categoryId || !searchInfo.categoryId)
  dataList = dataList.filter(item => item.status === searchInfo.status || !searchInfo.status)
  dataList = dataList.reverse()
  for (const film of dataList) {
    const res1 = getActorByIdAjax(film.actorId)
    film.actor = { ...res1.data }
  }
  for (const film of dataList) {
    const res2 = getCategoryByIdAjax(film.categoryId)
    film.category = { ...res2.data }
  }
  console.log(dataList)
  return Json.success(dataList)
}

export function deleteFilmAjax (id) {
  if (id === 1) {
    return Json.error('管理员禁止删除')
  }
  const index = getIndexById(id)
  filmList.splice(index, 1)
  return Json.success()
}

export function getFilmByIdAjax (id) {
  const index = getIndexById(id)
  return Json.success({ ...filmList[index] })
}

export function saveOrUpdate (formData = {}) {
  if (formData.id) {
    const index = getIndexById(formData.id)
    filmList[index] = { ...formData }
  } else {
    for (const film of filmList) {
      if (film.name === formData.name) {
        return Json.error('电影已存在')
      }
    }
    formData.id = AutoId.filmId
    filmList.push(formData)
    AutoId.filmId++
  }
  return Json.success()
}
